<template>
	<div>
		<div v-if="Object.keys(teamAgent).length > 0">
			<RateTable :agentInfo="teamAgent" @back="handleBack" />
		</div>
		<div class="breadcrumb" v-if="Object.keys(teamAgent).length > 0">
			<span>
				当前层级：
			</span>
			<template v-if="subAgents.length > 0">
				<div
					class="subAgents"
					v-for="(agent, index) in subAgents"
					:key="agent.id"
				>
					<el-link @click="handleBack(agent, index)" type="primary">
						{{ agent.userName }}{{ index === 0 ? '的团队' : '' }}
					</el-link>

					<span v-if="index < subAgents.length - 1">
						>
					</span>
				</div>
			</template>
		</div>
		<el-form ref="form" :rules="rules" :model="formData">
			<TableContainer
				:columns="columns"
				v-bind="tableProps"
				:tableHeight="tableHeight"
			/>
		</el-form>
		<RebateDialog
			:isEdit="rebateDialog.isEdit"
			:visible.sync="rebateDialog.visible"
			:teamAgent="teamAgent"
			:row="rebateDialog.row"
			@refresh="refresh"
		/>
	</div>
</template>
<script>
import TableContainer, {
	manager,
	initTableProps,
	TableColumns
} from '@/components/TableContainer'
import RateTable from '../rateTable'
import list from '@/mixins/list'
import RebateDialog from '../rebateDialog'

export default {
	name: 'Table',
	components: {
		TableContainer,
		RateTable,
		RebateDialog
	},
	mixins: [list],
	props: {
		formatParams: {
			type: Function,
			default: null
		},
		searchFormValues: {
			type: Object,
			default: null
		},
		tableHeight: {
			type: String | Number,
			default: 480
		}
	},
	data() {
		const headerRender = (label, tips, subLable) => {
			const _subLable =
				subLable || (this.showSubType === 2 ? '个人返水' : '团队返点')
			return (
				<div class='header'>
					{label}
					<div>{_subLable}</div>
					{tips && this.showSubType !== 2 && (
						<el-tooltip
							content={`${label}${_subLable}：${tips}`}
							placement='top-start'
							effect='dark'
						>
							<i class='el-icon-question' />
						</el-tooltip>
					)}
				</div>
			)
		}

		const rebateRender = ({ row, column }) => {
			const num = this.filterSummar4(row[column.property])
			if (row.status === 2) {
				return `${Number(num)}%`
			}
			if (row.status === 0) {
				return '-'
			}
			if (row.status === 3 && num < 0) {
				return '-'
			}
			return `${Number(num)}%`
		}

		const editRender = ({ row, column }) => {
			const prop = column.property
			return (
				<el-form-item prop={prop} class='form-item'>
					<div class='edit-number'>
						<el-input-number
							v-model={this.formData[prop]}
							precision={3}
							step={0.1}
							min={0}
							placeholder={Number(row[prop])}
							class='agen-input-number'
						/>
						<span>%</span>
					</div>
				</el-form-item>
			)
		}
		const rebateRule = [
			{
				validator: (rule, value, callback) => {
					const maxLimit = this.maxRebateLimit[rule.field]
					// const minLimit = this.minRebateLimit[rule.field] || 0
					const minLimit = 0 // 总代没有下限，输入0也可以验证通过
					if (!value && parseFloat(value) !== 0) {
						return callback(new Error(`不能为空`))
					}
					if (parseFloat(value) < minLimit) {
						return callback(
							new Error(`返点比例范围:${minLimit}~${maxLimit}`)
						)
					}
					if (parseFloat(value) > maxLimit) {
						return callback(
							new Error(`返点比例范围:${minLimit}~${maxLimit}`)
						)
					}
					return callback()
				},
				trigger: 'blur'
			}
		]

		return {
			showSubType: 0, // 0显示团队，1显示下级，2显示会员,
			maxRebateLimit: {},
			minRebateLimit: {},
			subAgents: [],
			teamAgent: {},
			// 当前选中编辑的行
			activeRow: {},
			rebateDialog: {
				visible: false,
				userType: 0,
				row: {}
			},
			rules: {
				texasRebate: rebateRule,
				sportsRebate: rebateRule,
				actualPersonRebate: rebateRule,
				esportsRebate: rebateRule,
				lotteryTicketRebate: rebateRule,
				chessRebate: rebateRule,
				texasInsuranceRebate: rebateRule
			},
			formData: {
				texasRebate: undefined,
				sportsRebate: undefined,
				actualPersonRebate: undefined,
				esportsRebate: undefined,
				lotteryTicketRebate: undefined,
				chessRebate: undefined,
				texasInsuranceRebate: undefined,
				remark: undefined
			},
			columns: [
				{
					label: '账号',
					prop: 'userName'
				},
				{
					label: '代理层级',
					prop: 'proxyLevel',
					customRender: ({ row }) => {
						if (row.userType === 0) {
							return '会员'
						}
						return row.proxyLevel.toString()
					}
				},
				{
					label: '所属商户',
					prop: 'merchantName'
				},
				{
					label: '所属总代',
					prop: 'topProxyName'
				},
				TableColumns.edit({
					prop: 'texasRebate',
					header: () =>
						headerRender(
							'德州-俱乐部',
							this.$t('agent.texasRebate_tips')
						),
					customRender: rebateRender,
					editRender
				}),
				TableColumns.edit({
					prop: 'texasInsuranceRebate',
					header: () =>
						headerRender(
							'德州-保险',
							this.$t('agent.texasInsuranceRebate_tips'),
							'团队分成'
						),
					isShow: () => {
						return this.showSubType !== 2
					},
					customRender: rebateRender,
					editRender
				}),
				TableColumns.edit({
					header: () => headerRender('真人'),
					prop: 'actualPersonRebate',
					minWidth: 150,
					customRender: rebateRender,
					editRender
				}),
				TableColumns.edit({
					header: () => headerRender('体育'),
					prop: 'sportsRebate',
					minWidth: 150,
					customRender: rebateRender,
					editRender
				}),
				TableColumns.edit({
					header: () => headerRender('彩票'),
					prop: 'lotteryTicketRebate',
					minWidth: 150,
					customRender: rebateRender,
					editRender
				}),
				TableColumns.edit({
					header: () => headerRender('棋牌'),
					prop: 'chessRebate',
					minWidth: 150,
					customRender: rebateRender,
					editRender
				}),
				TableColumns.edit({
					header: () => headerRender('电竞'),
					prop: 'esportsRebate',
					minWidth: 150,
					customRender: rebateRender,
					editRender
				}),
				TableColumns.status({
					minWidth: 80,
					texts: {
						0: '未设置',
						1: '已生效',
						2: '已失效',
						3: '平台调整'
					}
				}),
				{
					label: '修改时间',
					prop: 'updatedAt',
					minWidth: 170
				},
				{
					label: '失效时间',
					prop: 'lostEffectDt',
					minWidth: 170
				},
				{
					label: '修改人',
					prop: 'updatedBy'
				},
				TableColumns.edit({
					label: '备注',
					prop: 'remark',
					minWidth: 200,
					editRender: () => {
						return (
							<el-form-item prop='remark' class='form-item'>
								<el-input
									v-model={this.formData.remark}
									maxlength={50}
									placeholder='可以填写备注信息'
									show-word-limit
									type='textarea'
								/>
							</el-form-item>
						)
					}
				}),
				TableColumns.actions({
					minWidth: 220,
					fixed: 'right',
					editBtns: [
						({ row }) => {
							row.isEdit = false
							this.handleRowCancel(row)
						},
						({ row }) => {
							this.handleRowSubmit(row)
						}
					],
					btns: [
						{
							text: '查看下级',
							isShow: ({ row }) => row.userType === 1,
							onClick: ({ row }) => {
								row['showSubType'] = 1
								this.handleViewAgent(row)
							}
						},
						{
							text: `查看会员`,
							isShow: ({ row }) => row.userType === 1,
							onClick: ({ row }) => {
								row['showSubType'] = 2
								this.handleViewVip(row)
							}
						},
						// 会员修改
						{
							text: '修改',
							isShow: ({ row }) => row.userType === 0,
							disabled: ({ row }) => {
								return row.status === 2
							},
							onClick: ({ row }) => {
								this.handleRebateEdit(row)
							}
						},
						// 代理修改
						{
							text: '修改',
							isShow: ({ row }) => row.userType === 1,
							disabled: ({ row }) => {
								return row.status === 2 || row.proxyLevel > 0
							},
							onClick: ({ row }) => {
								this.handleRebateEdit(row)
							}
						}
					]
				})
			],
			tableProps: initTableProps(),
			listQueryParams: {}
		}
	},
	computed: {
		apiParams() {
			return {
				...this.formatParams(),
				userName: undefined,
				parentProxyName: this.searchFormValues.userName,
				userType: this.showSubType === 2 ? 0 : 1
			}
		}
	},
	created() {
		const { query } = this.$route
		if (query.userType) {
			this.teamAgent = query
			this.subAgents = [{ ...query }]
		}
		const { fetchApi, batchUpdateRowValue } = manager({
			api: this.$api.rebateRateListApi,
			tableProps: this.tableProps, // table props
			defaultParams: this.apiParams
		})
		this.search = (params) => {
			this.listQueryParams = params
			fetchApi({
				userType: this.showSubType === 2 ? 0 : 1,
				...params
			})
		}
		this.batchUpdateRowValue = batchUpdateRowValue
	},
	methods: {
		async handleRebateEdit(row) {
			this.rebateDialog.visible = true
			this.rebateDialog.row = row
			this.rebateDialog.isEdit = true
		},
		async handleRowEdit(row) {
			await this.queryMinLimit(row)
			await this.queryMaxLimit(row)
			this.batchUpdateRowValue('isEdit', false)
			row.isEdit = true
			this.activeRow = row
			const _self = this
			Object.keys(_self.formData).forEach((k) => {
				if (row.status === 3 && row[k]) {
					_self.formData[k] =
						parseFloat(row[k].toString('').replace('-', '')) || 0
					return
				}

				_self.formData[k] = row[k]
					? row[k]
					: k === 'remark'
					? undefined
					: 0
			})
		},
		refresh() {
			// const actionItem = this.subAgents[this.subAgents.length - 1]
			this.search(this.listQueryParams)
		},
		handleRowCancel(row) {
			Object.keys(this.formData).forEach((k) => {
				this.formData[k] = undefined
			})
		},
		handleViewAgent(row) {
			this.showSubType = 1
			if (this.subAgents.length === 0) {
				this.teamAgent = row
				console.log(row)
			}
			this.subAgents.push(row)
			this.tableProps.pageNum = 1
			this.tableProps.pageSize = 100
			this.search({
				parentProxyName: row.userName,
				userType: 1
			})
		},
		handleViewVip(row) {
			this.showSubType = 2
			this.teamAgent = row
			this.subAgents.push(row)
			const parmas = {
				parentProxyName: row.userName,
				userType: 0
			}

			if (row.status === 2) {
				parmas['status'] = 2
			}
			this.tableProps.pageNum = 1
			this.tableProps.pageSize = 100
			this.search(parmas)
		},
		handleBack(agent, index) {
			this.tableProps.pageNum = 1
			this.tableProps.pageSize = 100
			if (agent === undefined) {
				this.search({
					...this.formatParams(),
					userType: 1
				})
				this.showSubType = 0
				this.teamAgent = {}
				this.subAgents = []
				return
			}
			this.showSubType = agent.showSubType
			this.subAgents = this.subAgents.filter((item, _index) => {
				return _index <= index
			})
			const actionItem = this.subAgents[this.subAgents.length - 1]
			this.search({
				parentProxyName: actionItem.userName,
				userType: agent.showSubType === 2 ? 0 : 1
			})
		},
		async queryRebateRate(userName) {
			try {
				const res = await this.$api.rebateRateQuery({
					userType: 1,
					userName: userName,
					status: 1
				})
				return res
			} catch (err) {
				throw err
			}
		},
		async filter(params) {
			this.handleBack()
		},
		rowSubmitConfirm() {
			const msg =
				'确认修改返点比例后，针对待结算返点账单即刻生效。修改前返点比例将生成已失效记录。'
			const title = '确认修改返点比例'
			return this.$confirm(msg, title)
		},
		async handleRowSubmit(row) {
			try {
				await this.$refs['form'].validate()
				// await this.rowSubmitConfirm()
				let isAllNull = true
				Object.keys(this.formData).forEach((k) => {
					if (k !== 'remark' && this.formData[k] > 0) {
						isAllNull = false
					}
				})
				if (isAllNull) {
					this.$message.error(
						'全部场馆项目不能全为0，至少1个场馆值>0'
					)
					return
				}
				this.agentPointSetAllSub.visible = true
				this.agentPointSetAllSub.agentPoint = this.formData
				this.agentPointSetAllSub.agentData = {
					// ...row,
					merchantId: row.merchantId,
					id: row.topProxyId,
					topProxyName: row.topProxyName
				}
				this.agentPointSetAllSubVisible = true
				this.agentPointSetAllSubVisible = {
					...this.formData
				}
			} catch (err) {
				throw err
			}
		},
		async queryMinLimit(row) {
			const res = await this.$api.rebateQuerySubMax({
				parentProxyName: row.userName
			})
			if (res.code === 200) {
				this.minRebateLimit = res.data || {}
			}
		},
		async queryMaxLimit(row) {
			if (row.parentProxyName) {
				const res = await this.$api.rebateRateQuery({
					userName: row.parentProxyName,
					status: 1,
					userType: 1
				})
				if (res.code === 200 && res.data.length > 0) {
					this.maxRebateLimit = res.data[0] || {}
				}
			} else {
				const res = await this.$api.rebateRateQueryLimit({
					platformFlag: 0
				})
				if (res.code === 200 && res.data) {
					this.maxRebateLimit = res.data || {}
				}
			}
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep {
	.el-form-item__error {
		white-space: nowrap;
	}
}
::v-deep .edit-number {
	.el-input-number__decrease {
		display: none;
	}
	.el-input-number__increase {
		display: none;
	}

	.el-input-number .el-input__inner {
		padding: 0;
	}

	.el-input-number {
		width: 80px;
	}
}
.subAgents {
	display: flex;
	align-items: center;
	a {
		font-size: 15px;
	}
	span {
		margin: 0 4px;
	}
}
.breadcrumb {
	display: flex;
	margin-top: 40px;
	margin-bottom: 10px;
	span {
		color: #9b9ca0;
		font-size: 14px;
	}
}
.header {
	position: relative;

	.el-icon-question {
		position: absolute;
		font-size: 12px;
		top: 25px;
		right: 5px;
		cursor: pointer;
		&:after {
			font-size: 17px;
		}
	}
}
</style>
